package com.leadingsoft.controller.browser.impl;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import org.apache.commons.lang3.StringUtils;
import org.cef.CefApp;
import org.cef.CefClient;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.handler.CefLoadHandlerAdapter;

import com.leadingsoft.common.CheckUrl;
import com.leadingsoft.common.Constant;
import com.leadingsoft.common.TaskQuene;
import com.leadingsoft.controller.browser.BrowserInstance;
import com.leadingsoft.controller.parse.DownloadHtmlDocument;
import com.leadingsoft.ui.BrowserFrame;

/**
 * @ClassName ButtonBrowserInstance
 * @Description Button浏览器实例<br>
 *              进行数据抓取<br>
 *              下一页是通过点击页面下一页按钮进行获取
 * @author gongym
 * @date 2018年6月7日 下午5:09:30
 */
public class ButtonBrowserInstance implements BrowserInstance {
	private CefClient nowClient;
	private Boolean nowOsrEnabled;
	private Boolean nowTransparentPaintingEnabled;

	public ButtonBrowserInstance(CefClient client, boolean osrEnabled, boolean transparentPaintingEnabled) {
		this.nowClient = client;
		this.nowOsrEnabled = osrEnabled;
		this.nowTransparentPaintingEnabled = transparentPaintingEnabled;
	}
	/**
	 * @Title createBrowserAndCrawler
	 * @Description 创建浏览器实例
	 * @param startIndex
	 * @param stopIndex
	 * @return void
	 */
	public void createBrowserAndCrawler(Long startIndex, Long stopIndex) {
		// 给一个起始页创建浏览器对象
		CefBrowser browser = nowClient.createBrowser("http://www.baidu.com", nowOsrEnabled,
				nowTransparentPaintingEnabled);
		nowClient.addLoadHandler(new CefLoadHandlerAdapter() {
			@Override
			public void onLoadEnd(CefBrowser browser, CefFrame frame, int what) {
				String url = browser.getURL();
				if (CheckUrl.isListUrl(url)) {
					String index = StringUtils.remove(url, Constant.CTRIPHOTELLISTUTLTEMP);
					DownloadHtmlDocument htmlSource = new DownloadHtmlDocument(url);
					browser.getSource(htmlSource);
					Long nextIndex = Long.parseLong(index) + 1;
					if (nextIndex <= stopIndex) {
						// 上一个页面一已经抓取完了，需要使页面加载下一页
						// 执行一些操作
					} else {
						// 当前任务结束
						// 关闭浏览器
						browser.close();
					}
				} else {
					StringBuilder startUrl = new StringBuilder(Constant.CTRIPHOTELLISTUTLTEMP);
					startUrl.append(startIndex);
					TaskQuene.taskUrl.add(startUrl.toString());
				}
			}
		});
		final BrowserFrame frame = new BrowserFrame(nowClient, browser);
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				frame.dispose();
				CefApp.getInstance().dispose();
			}
		});
		frame.setSize(1000, 500);
		frame.setVisible(true);
		// 开始抓取数据
		crawlerData(browser);
	}
	/**
	 * @Title crawlerData
	 * @Description 循环列表抓取数据
	 * @param startIndex
	 * @param stopIndex
	 * @return void
	 */
	private void crawlerData(CefBrowser browser) {
	}
}
